<template>
	<view class="content">
		<el-form id="pdfDom" :model="admitInfo" ref="admitFormRef" label-position="top">
			<!-- <el-form-item v-if="!isAdd">
				<el-row type="flex" justify="end">
					<el-button type="default" @click="editDetails">
						<Icon class="mr-5rpx" icon="ep:edit" />{{ $t(`global.edit`) }}
					</el-button>
					<el-button type="default" @click="shareLink">
						<Icon class="mr-5rpx" icon="ep:share" />{{ $t(`global.share`) }}
					</el-button>
					<el-button v-if="!isAdd" type="danger" @click="deleteAdmit">
						<Icon class="mr-5rpx" icon="ep:delete" />{{ $t(`global.delete`) }}
					</el-button>
				</el-row>
			</el-form-item> -->
			<el-row :gutter="10">
				<el-text class="title">{{ admitInfo.id }}</el-text>
				<el-col :span="24">
					<el-form-item :label="$t(`admitDetail.from.id`)">
						<el-text>{{ admitInfo.id }}</el-text>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item :label="$t(`admitDetail.from.admitTime`)">
						<span v-if="!isEdit && !isAdd">{{ formatDate(admitInfo.receptionTime) }}</span>
						<el-date-picker v-else v-model="admitInfo.receptionTime" type="datetime"
							:placeholder="$t(`global.select`)" style="width: 100%;" />
					</el-form-item>
				</el-col>
				<el-col :span="24" v-if="isAdd || isEdit">
					<el-form-item :label="$t(`admitDetail.from.scan`)">
						<el-upload action="#" :file-list="fileDetailList" :auto-upload="false" :multiple="false"
							:show-file-list="false" :on-change="onchangeFile" style="width: 100%;" class="line_flex">
							<el-button style="width: 100%; font-weight: 600;" @click="scanCard">
								<Icon class="mr-5px" icon="ep:postcard" />{{ $t(`global.recognition`) }}
							</el-button>
						</el-upload>
					</el-form-item>
				</el-col>
			</el-row>
			<el-collapse v-model="activeNames">
				<el-collapse-item name="1">
					<template #title>
						<el-text class="form_sub_title">{{ $t(`admitDetail.from.receiver.title`) }}</el-text>
					</template>
					<el-row :gutter="10">
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.receiver.name`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.contactsName }}</span>
								<el-input v-model="admitInfo.contactsName" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.receiver.position`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.contactsPosition }}</span>
								<el-input v-model="admitInfo.contactsPosition" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.receiver.phone`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.contactsPhone }}</span>
								<el-input v-model="admitInfo.contactsPhone" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.receiver.email`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.contactsEmail }}</span>
								<el-input v-model="admitInfo.contactsEmail" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.receiver.adress`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.contactsAddress }}</span>
								<el-input v-model="admitInfo.contactsAddress" v-else />
							</el-form-item>
						</el-col>
					</el-row>
				</el-collapse-item>
				<el-collapse-item name="2">
					<template #title>
						<el-text class="form_sub_title">{{ $t(`admitDetail.from.client.title`) }}</el-text>
					</template>
					<el-row :gutter="10">
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.client.companyName`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.companyName }}</span>
								<el-input v-model="admitInfo.companyName" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.client.name`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.name }}</span>
								<el-input v-model="admitInfo.name" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.client.position`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.postion }}</span>
								<el-input v-model="admitInfo.postion" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.client.telephone`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.landlineTelephone }}</span>
								<el-input v-model="admitInfo.landlineTelephone" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.client.phone`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.phoneNumber }}</span>
								<el-input v-model="admitInfo.phoneNumber" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.client.email`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.email }}</span>
								<el-input v-model="admitInfo.email" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.client.adress`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.companyAddress }}</span>
								<el-input v-model="admitInfo.companyAddress" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.client.website`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.companyWebsite }}</span>
								<el-input v-model="admitInfo.companyWebsite" v-else />
							</el-form-item>
						</el-col>
						<el-col :span="24" v-if="admitInfo.cardScanFilePath">
							<el-form-item :label="$t(`admitDetail.from.client.card`)">
								<el-image :preview-src-list="[admitInfo.cardScanFilePath]"
									:src="admitInfo.cardScanFilePath" style="width: 300px;height:180px;" />
							</el-form-item>
						</el-col>
					</el-row>
				</el-collapse-item>
				<el-collapse-item name="3">
					<template #title>
						<el-text class="form_sub_title">{{ $t(`admitDetail.from.goods`) }}</el-text>
					</template>
					<el-row>
						<el-col :span="24">
							<el-form-item>
								<proList v-model="admitInfo.customerGoodss" :readonly="!isAdd && !isEdit" />
							</el-form-item>
						</el-col>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.remark`)">
								<span v-if="!isEdit && !isAdd">{{ admitInfo.memo }}</span>
								<el-input type="textarea" v-model="admitInfo.memo" v-else />
							</el-form-item>
						</el-col>
					</el-row>
				</el-collapse-item>
				<el-collapse-item name="4">
					<template #title>
						<el-text class="form_sub_title">{{ $t(`admitDetail.from.summarize`) }}</el-text>
					</template>
					<el-row>
						<el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.tag`)">
								<el-select v-model="admitInfo.tags" multiple filterable allow-create
									default-first-option :disabled="!isEdit && !isAdd" :reserve-keyword="false"
									:placeholder="$t(`global.select`)" style="width: 100%" @change="addTag">
									<el-option v-for="item in options" :key="item.value" :label="item.label"
										:value="item.value" />
								</el-select>
							</el-form-item>
						</el-col>
						<!-- <el-col :span="24">
							<el-form-item :label="$t(`admitDetail.from.id`)" v-if="showAdmitDetail">
								<span v-if="!isEdit && !isAdd" v-html="admitInfo.summary"></span>
								&lt;!&ndash;富文本编辑器组件&ndash;&gt;
								<Editor v-model="admitInfo.summary" v-else :toolConfig="toolbarConfig" style="width: 100%"
									height="300px" />
								<view @click="startRecord">
									<button>开始录音</button>
								</view>
								<view @click="pauseRecord">
									<el-button>暂停录音</el-button>
								</view>
								<view @click="stopRecord">
									<button>结束录音</button>
								</view>
							</el-form-item>
						</el-col> -->
					</el-row>
				</el-collapse-item>
				<el-collapse-item name="5">
					<template #title>
						<el-text class="form_sub_title">{{ $t(`admitDetail.from.history.title`) }}</el-text>
					</template>
					<el-table :data="viewList" :border="true">
						<el-table-column :label="$t(`admitDetail.from.history.lookTime`)" prop="checkTime" />
						<el-table-column :label="$t(`admitDetail.from.history.ipAdress`)" prop="ip" />
						<el-table-column :label="$t(`admitDetail.from.history.lookAdress`)" prop="address" />
					</el-table>
				</el-collapse-item>
			</el-collapse>
		</el-form>
		<el-row type="flex" justify="center" class="guding">
			<el-button type="primary" @click="editDetails" v-if="!isEdit">{{ $t(`global.edit`) }}</el-button>
			<el-button type="primary" v-if="isEdit || isAdd" @click="submitForm">{{ $t(`global.verify`) }}</el-button>
			<el-button @click="cacel">{{ $t(`global.cancel`) }}</el-button>
		</el-row>
	</view>

	<el-dialog v-model="shareDialog" @closed="cacelShare">
		<el-input v-model="shareLinks" />
		<el-row type="flex" justify="center" style="margin-top: 20px">
			<el-button type="primary" @click="copyLink">复制链接</el-button>
			<el-button @click="cacelShare">{{ $t(`global.cancel`) }}</el-button>
		</el-row>
	</el-dialog>

	<uni-popup ref="popup" background-color="#fff" border-radius="10px 10px 0 0">
		<uni-row class="demo-uni-row">
			<uni-col :span="24">
				<el-button type="info" :icon="Share" text @click="shareLink">&nbsp&nbsp&nbsp&nbsp{{ $t(`global.share`)
					}}</el-button>
			</uni-col>
			<uni-col :span="24" style="margin-top: 10px;">
				<el-button type="info" :icon="Delete" text @click="deleteAdmit">&nbsp&nbsp&nbsp&nbsp{{
					$t(`global.delete`)
				}}</el-button>
			</uni-col>
		</uni-row>
	</uni-popup>
</template>
<script lang="ts" setup>
import { Delete, Share } from '@element-plus/icons-vue'
import { FormInstance } from "element-plus";
import proList from '@/pages/hkb/components/proList/index.vue'
import * as admitApi from '@/service/api/hkb/admit/index'
import { ref } from 'vue'
import type { AdmitVO, ColumnVO, ViewListVO } from '../types'
import { createDictData, DictDataVO, getDictData, getDictDataPage } from "@/service/api/system/dict/dict.data";
import { goodsVO } from "../types";
import * as fileUpload from '@/service/api/infra/file'
import { useRouter } from 'vue-router';
import axios from 'axios';
import { createView } from "@/service/api/hkb/view";
import { getBusinessCardInfo } from "@/service/api/hkb/admit/index";
import Storage from "@/modal/useStorage";
import { formatDate } from '@/utils/formatTime'
import i18n from '@/main'
import { Navigate } from '@/utils';
import { REFRESH_CONFIG, getServiceEnvConfig } from '@/config'
const { url } = getServiceEnvConfig(import.meta.env)
onLoad(() => {
	const admitDetail = Storage.get('admitDetail')
	isAdd.value = admitDetail.isAdd
	isEdit.value = admitDetail.isEdit
	if (isAdd.value) {
		uni.setNavigationBarTitle({
			title: i18n.global.locale === 'zh' ? '新增客户接待' : 'ADDADMIT'
		})
		Storage.set('selectGoods', [])
	} else {
		uni.setNavigationBarTitle({
			title: i18n.global.locale === 'zh' ? '接待详情' : 'ADMITDETAIL'
		});
		Storage.set('selectGoods', admitDetail.admit.list)
	}
	if (admitDetail.admit) {
		admitInfo.value = admitDetail.admit
	}
})
const router = useRouter()

const showDetail = ref(false)
const showAdmitDetail = ref(true)
const isAdd = ref(true) //是否新增
const isEdit = ref(false) //是否编辑
const childRef = ref()
const loading = ref(false) // 列表的加载中
const buttonLoading = ref(false) //按钮的加载
const total = ref(0) // 列表的总页数
const activeNames = ref(['2', '3', '4'])
const list = ref<AdmitVO[]>([]) // 列表的数据
const viewList = ref<ViewListVO[]>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileDetailList = ref<any[]>([])
const accessDetail = ref(false)
const message = useMessage() // 消息弹窗
// const recorderManager = uni.getRecorderManager();
// const innerAudioContext = uni.createInnerAudioContext();
// const fileSystemManager = uni.getFileSystemManager();

const allCol = ref<ColumnVO[]>([
	{ label: '自动编号', prop: 'id', width: '' },
	{ label: '接待时间', prop: 'receptionTime', width: '' },
	{ label: '标签', prop: 'tags', width: '200px' },
	{ label: '公司名称', prop: 'companyName', width: '' },
	{ label: '姓名', prop: 'name', width: '' },
	{ label: '名片', prop: 'cardScanFilePath', width: '' },
	{ label: '商品信息', prop: 'customerGoodss', width: '' },
	{ label: '查看次数', prop: 'hislist', width: '' },
	{ label: '创建人', prop: 'creator', width: '' }
])
const checkCol = ref<ColumnVO[]>([])
const checked = ref([])

const options = ref([])

const popup = ref()
onNavigationBarButtonTap(async (e) => {
	popup.value.open('bottom');
})


const queryParams = ref({
	pageNum: 1,
	pageSize: 10
}) // 查询参数

const singleView = ref<ViewListVO>({
	checkTime: '',
	ip: '',
	address: '',
	viewType: '',
	sampleid: '',
})

const dictqueryParams = ref({
	pageNum: 1,
	pageSize: 100,
	dictType: 'hkb_admint_tag',
}) // 字典查询参数

const dictData = ref<DictDataVO>({
	dictType: 'hkb_admint_tag',
	label: '',
	value: '',
	status: 0,
	sort: 4,
})

import { IToolbarConfig } from '@wangeditor/editor'
const toolbarConfig: Partial<IToolbarConfig> = {
	excludeKeys: [
		'uploadVideo', // 排除菜单组，写菜单组 key 的值即可
		"group-video",
		'group-image',
		'emotion',
		'todo',
		'insertLink',
		'insertTable',
		'divider',
		'codeBlock'
	]
}

const admitFormRef = ref<FormInstance>()
const admitInfo = ref<AdmitVO>({
	id: '',
	automaticNumber: '',
	receptionTime: '',
	tags: [],
	companyName: '',
	landlineTelephone: '',
	phoneNumber: '',
	address: '',
	companyWebsite: '',
	name: '',
	postion: '',
	contactNumber: '',
	email: '',
	companyAddress: '',
	cardScanFileName: '',
	cardScanFilePath: '',
	cardScan: '',
	recordFileId: '',
	recordFileName: '',
	recordFilePath: '',
	comment: '',
	customerGoodss: [],
	summary: '',
	contactsName: '',
	contactsPhone: '',
	contactsPosition: '',
	contactsEmail: '',
	contactsAddress: '',
})
const admitInfoInitForm = ref<AdmitVO>({
	id: '',
	automaticNumber: '',
	receptionTime: '',
	tags: [],
	companyName: '',
	landlineTelephone: '',
	phoneNumber: '',
	address: '',
	companyWebsite: '',
	name: '',
	postion: '',
	contactNumber: '',
	email: '',
	companyAddress: '',
	cardScanFileName: '',
	cardScanFilePath: '',
	cardScan: '',
	recordFileId: '',
	comment: '',
	recordFileName: '',
	recordFilePath: '',
	customerGoodss: [],
	summary: '',
	contactsName: '',
	contactsPhone: '',
	contactsPosition: '',
	contactsEmail: '',
	contactsAddress: '',
})
const getList = async () => {
	const res = await admitApi.getList(queryParams.value)
	console.log(res)
	if (res.list.length > 0) {
		res.list.forEach(e => {
			e.customerGoodss = e.customerGoodss.filter(g => g)
		})
		list.value = res.list
		total.value = res.total
	}
	getTagList()
}

const getTagList = async () => {
	const tagList = await getDictDataPage(dictqueryParams.value)
	if (tagList.total > 0) {
		options.value = tagList.list
	}
}

//新加标签
const addTag = () => {
	admitInfo.value.tags.map(item => {
		if (options.value.findIndex(o => o.value === item) < 0) {
			dictData.value.label = item
			dictData.value.value = item
			createDictData(dictData.value)
			getTagList()
		}
	})
}

/** 记录分享访问次数 **/
const countShare = async () => {
	let id = router.currentRoute.value.query.shareId
	if (id) {
		try {
			const response = await axios.get?.('https://qifu-api.baidubce.com/ip/local/geo/v1/district');
			singleView.value.checkTime = new Date()
			singleView.value.ip = response.data.ip
			singleView.value.address = response.data.data.prov + response.data.data.city + response.data.data.district
			singleView.value.viewType = '2'
			singleView.value.sampleid = id
		} catch (error) {
			console.error('请求错误', error);
			return null;
		}
		console.log(singleView)
		const res = await createView(singleView.value)
		let sharedPro = list.value.find(item => item.id === parseFloat(id))
		admitDetails(sharedPro)
	}
}

//提交接待
const submitForm = async () => {
	admitInfo.value.customerGoodss?.map(item => {
		item.qrcode = ''
		return item
	})
	admitFormRef.value?.validate(async (valid: boolean) => {
		if (valid) {
			buttonLoading.value = true;
			if (admitInfo.value.id) {
				await admitApi.editAdmit(admitInfo.value).then((res) => {
					if (res) {
						message.success('修改成功')
					} else {
						message.warning('修改失败')
					}
				})
					.finally(() => (buttonLoading.value = false));
			} else {
				await admitApi.addAdmit(admitInfo.value).then((res) => {
					if (res) {
						message.success('新增成功')
					} else {
						message.warning('新增失败')
					}
				}).finally(() => (buttonLoading.value = false));
			}
			showAdmitDetail.value = false;
			Navigate.to('/pages/hkb/product/product')
		}
	})
}
/** 名片扫描 **/
const scanCard = () => {

}

/** 删除 **/
const deleteAdmit = async () => {
	try {
		// 二次确认
		await message.confirm('确认要立即删除这条数据吗?', '温馨提示')
		// 提交执行
		admitApi.deleteAdmit(admitInfo.value.id).then((res) => {
			if (res) {
				message.success('删除成功')
			} else {
				message.warning('删除失败')
			}
		}).finally(() => (cacel(), getList()))
	} catch (error) { }
}

/** 分享链接 **/
const shareLink = () => {
	// shareDialog.value = true
	shareLinks.value = window.location.href + '?shareId=' + productInfo.value.id
	uni.showModal({
		content: shareLinks.value,//模板中提示的内容
		confirmText: '复制内容',
		success: () => {//点击复制内容的后调函数
			//uni.setClipboardData方法就是讲内容复制到粘贴板
			uni.setClipboardData({
				data: shareLinks.value,//要被复制的内容
				success: () => {//复制成功的回调函数
					uni.showToast({//提示
						title: '复制成功'
					})
				}
			});
		}
	});
}

//详情
const admitDetails = (row) => {
	isEdit.value = false
	isAdd.value = false
	showAdmitDetail.value = true
	viewList.value = row?.hislist
	viewList.value.map(item => {
		item.checkTime = new Date(item.checkTime).toLocaleString()
		return item
	})
	admitInfo.value = row
}

/** 编辑接待 **/
const editDetails = () => {
	isEdit.value = true
	isAdd.value = false
}

/** 查看商品详情 **/
const proDetails = (row) => {
	isEdit.value = false
	isAdd.value = false
	showDetail.value = true
	childRef.value.initFormValue(row)
}

//显示新增
const showAdd = async () => {
	isEdit.value = false
	isAdd.value = true
	showAdmitDetail.value = true
}

const showAccess = () => {
	accessDetail.value = true
}

//关闭弹窗
const cacel = () => {
	Navigate.to('/pages/hkb/product/product')
}

/** 添加文件到文件列表 **/
const onchangeFile = async (file: any) => {
	fileDetailList.value.push(file)
	let formdata = new FormData()
	formdata.append('files', file.raw)
	const res = await fileUpload.updateFileBatch(formdata)
	let cardPath = url + '/' + res.data.data[0].url
	let cardName = url + '/' + res.data.data[0].name
	admitInfo.value.cardScanFilePath = cardPath
	admitInfo.value.cardScanFileName = cardName
	if (cardPath) {
		let path = encodeURIComponent(cardPath)
		const res1 = await admitApi.getBusinessCardInfo(path)
		let data = JSON.parse(res1).result.item_list
		console.log(data)
		admitInfo.value.companyName = data.find(item => item.description === '公司').value
		admitInfo.value.companyAddress = data.find(item => item.description === '地址').value
		admitInfo.value.companyWebsite = data.find(item => item.description === '网址').value
		admitInfo.value.landlineTelephone = data.find(item => item.description === '电话').value
		admitInfo.value.name = data.find(item => item.description === '姓名').value
		admitInfo.value.postion = data.find(item => item.description === '职称').value
		admitInfo.value.phoneNumber = data.find(item => item.description === '手机').value
		admitInfo.value.email = data.find(item => item.description === '邮件').value
	}
}

const startRecord = () => {
	recorderManager.start({ sampleRate: 8000 })
}

const pauseRecord = () => {
	recorderManager.pause()
}

const stopRecord = () => {
	recorderManager.stop()
	recorderManager.onStop(function (res) {
		console.log(res.tempFilePath)
		// getFileInfo(res.tempFilePath)
		// let recordPath = import.meta.env.VITE_BASE_URL + '/admin-api/' + res.tempFilePath
		// 	let formdata = new FormData()
		// 	formdata.append('files', file.raw)
		// 	const res = await fileUpload.updateFileBatch(formdata)
		// innerAudioContext.src = res.tempFilePath;
		// innerAudioContext.play();
		uni.uploadFile({
			url: '/infra/file/uploadBatch',
			filePath: res.tempFilePath,
			name: 'file',
			success: (uploadFileRes) => {
				console.log(uploadFileRes.data);
			}
		})
		//  plus.io.getFileInfo({
		//  	filePath: res.tempFilePath,
		// digestAlgorithm: 'md5',
		//  	success(res){
		//  		console.log(res);
		// 	let formdata = new FormData()
		// 	formdata.append('files', res)
		// 	fileUpload.updateFileBatch(formdata).then(res => {
		// 		console.log(res)
		// 	})
		//  		// console.log( `大小：${res.size / 1024 }K ` );
		//  	},
		//  	fail(err){
		//  		console.error( `获取文件信息失败: ${JSON.stringify(err)}` );
		//  	}
		//  })
	})
}

// const getFileInfo = (filePath: string) => {
// 				// 获取文件信息

// 			}


/** 激活时 */
onActivated(() => {
	getList()
})

/** 初始化 **/
onMounted(async () => {
	countShare()
	await getList()
	checkCol.value = JSON.parse(JSON.stringify(allCol.value))
	checked.value = JSON.parse(JSON.stringify(allCol.value.map((item) => item.label)))
})

</script>
<style lang="scss" scoped>
.content {
	background: #fff;
	padding: 0 20rpx;

	.title {
		font-size: 40rpx;
		margin: 20rpx 10rpx;
	}
}

.tableOp {
	margin-bottom: 10px;
}

.tag {
	margin: 5px 5px;
}

.form_sub_title {
	font-weight: 600;
}

::v-deep .line_flex .el-upload {
	display: flex;
}

.guding {
	position: fixed;
	bottom: 10px;
	right: 50px;
}

::v-deep .uni-popup__wrapper {
	padding: 10px;
}
</style>
